﻿Imports Microsoft.VisualBasic

Namespace MyDBase

    Public Module MyDBaseData

        ' TODO config
        Public Property AppDBStructure As mDB.Structure

    End Module


    Public Class mDB
        Inherits GloukDB
        'Const DBName = "DB_MAIN"

        Public Sub New(ByVal CnnString As String, DBStructure As DBase.MySql.DBStructureBase)
            MyBase.New(CnnString, DBStructure)
        End Sub

        Public Shared Function GetDBStructure() As DBase.MySql.DBStructureBase

            ' TODO config metto la struttura del DB in una variabile globale
            If AppDBStructure Is Nothing Then
                AppDBStructure = New mDB.Structure
            End If
            Return AppDBStructure

        End Function


        Public Shared Function GetDB() As mDB

            Return GetDB(True, HttpContext.Current)

        End Function

        'Public Shared Function GetDB(Auto As Boolean) As mDB

        '    Return GetDB(Auto, HttpContext.Current)

        'End Function

        Public Shared Function GetDB(Auto As Boolean, context As HttpContext) As mDB
            ' TODO config

            Dim CacheObjName = "DB_App_" & Threading.Thread.CurrentThread.ManagedThreadId

            Dim DB As mDB = Nothing

            If Auto Then

                'If context IsNot Nothing Then
                DB = context.Items(CacheObjName)
                'End If

                If DB Is Nothing Then
                    DB = NewDBObj(GetConnStr(context))
                    If context IsNot Nothing And Auto Then
                        context.Items(CacheObjName) = DB
                    End If
                End If

            Else
                DB = NewDBObj(GetConnStr(context))
            End If

            Return DB

        End Function
        Public Shared Function NewDBObj(ConnStr As String) As mDB

            Dim DB = New mDB(ConnStr, GetDBStructure)
            Dim ConfConn = Utils.Dictionary.StringToDictionary(ConnStr)
            DB.DBName = ConfConn("Database").ToUpper

            Return DB

        End Function
        Public Shared Function GetConnStr(context As HttpContext) As String

            Dim ConfKey As String = "APP"
            Select Case context.Request.Url.Host.ToUpper
                Case "BETA.GLOUK.IT"
                    ConfKey = "BETA"

            End Select
            Return Web.Configuration.WebConfigurationManager.ConnectionStrings(ConfKey).ToString

        End Function


    End Class

End Namespace
